<template>
    <el-main class="bodyBox" v-loading="showLoading">
		<el-form ref="actionform" :model="formData" label-width="80px">
			<div>
				<el-form-item label="名称" verify prop="productName">
                    <el-input
						class="formItem"
						type="textarea"
						v-model="formData.productName"
						:autosize="{ minRows: 1, maxRows: 4}"
						placeholder="商品名称"></el-input>
                </el-form-item>
                <el-form-item label="描述" verify prop="productDesc">
                    <el-input
						class="formItem"
						type="textarea"
						:autosize="{ minRows: 1, maxRows: 4}"
						v-model="formData.productDesc"
						placeholder="商品描述"></el-input>
                </el-form-item>
				<el-form-item label="商品分类" verify prop="categoryUid">
					<el-select
						v-model="formData.categoryUid"
						placeholder="请选择分类"
						size="small"
						@change="checkCategory">
						<el-option
							v-for="item in categoryDataList"
							:key="item.labelId"
                        	:label="item.labelText"
                        	:value="item.labelId"></el-option>
					</el-select>
                </el-form-item>
				<el-form-item label="商户列表" verify prop="storeUid">
					<el-select
						v-model="formData.storeUid"
						placeholder="请选择商户"
						size="small"
						@change="handleChange">
						<el-option
							v-for="item in storeList"
							:key="item.merchantUid"
							:label="item.merchantName"
							:value="item.merchantUid"></el-option>
					</el-select>
                </el-form-item>
                <el-form-item label="进价" verify prop="minPrice">
					<el-input-number v-model="formData.minPrice" class="formItem" :min="0" label="进价" />
                </el-form-item>
                <el-form-item label="原价" verify prop="originPrice">
					<el-input-number v-model="formData.originPrice" class="formItem" :min="0" label="原价" />
                </el-form-item>
                <el-form-item label="心意价" verify prop="salePrice">
					<el-input-number v-model="formData.salePrice" class="formItem" :min="0" label="心意价" />
                </el-form-item>
				 <el-form-item label="库存" verify prop="usableStock">
					<el-input-number v-model="formData.usableStock" class="formItem" :min="0" label="心意价" />
                </el-form-item>
				<el-form-item label="缩略图" prop="listImageUrl" verify>
                    <el-upload
                        :action="uploadUrl"
                        :data="access_token"
                        :show-file-list="false"
                        :before-upload="beforeUpload"
                        :on-success="uploadPreviewSuccess"
                    >
                     	<img :src="previewImageInfo.content" class="avatar" v-if="previewImageInfo.content" />
                  		<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						<el-input class="inputs none imgArea" v-model="formData.listImageUrl"></el-input>
					</el-upload>
                </el-form-item>
                <el-form-item label="轮播图" prop="campaignMainImageUrl">
                    <p style="display: flex;">
						<el-upload
							:action="uploadUrl"
							:data="access_token"
							ref="uploadBanners"
							:show-file-list="false"
							:before-upload="beforeUpload"
							:disabled="dragTags.length > 5"
							:on-exceed="handleExceed"
							multiple
							:limit="6"
							:on-success="uploadBannersSuccess"
						><el-button size="small" type="primary">上传</el-button></el-upload> <span style="margin-left: 20px">(最多6张)</span>
					</p>
                    <draggable v-model="dragTags" :move="getdata" @update="datadragEnd" :options="{animation:500}" class="imgBoxWarpGrid">
                        <div class="imgBoxWarpGrid-imgBox flex-center" v-for="(item, index) in dragTags" :key="index">
                            <img :src="item.content" class="avatar" v-if="item.content" />
							<div class="resource_auth">
								<el-input size="mini" v-model="item.sort" placeholder="请输入排序" class="resource_auth_number" />
							</div>
                            <div class="deleteIcons" @click="handleDel(index)">
                                <i class="el-icon-circle-close"></i>
                            </div>
                        </div>
                    </draggable>
                </el-form-item>
                <el-form-item label="详情图" prop="productDetails">
					<p style="display: flex;">
						<el-upload
							:action="uploadUrl"
							:data="access_token"
							:show-file-list="false"
							multiple
							:limit="12"
							ref="uploadDetails"
							:on-exceed="handleExceedMore"
							:disabled="dragTagsDetails.length > 11"
							:before-upload="beforeUpload"
							:on-success="uploadDetailsSuccess"
						><el-button size="small" type="primary">上传</el-button></el-upload> <span style="margin-left: 20px">(最多12张)</span>
					</p>
                    <draggable v-model="dragTagsDetails" :move="getdata" @update="datadragEnd" :options="{animation:500}" class="imgBoxWarpGrid">
                        <div class="imgBoxWarpGrid-imgBox flex-center" v-for="(item, index) in dragTagsDetails" :key="index">
                            <img :src="item.content" class="avatar" v-if="item.content" />
							<div class="resource_auth">
								<el-input size="mini" v-model="item.sort" placeholder="请输入排序" class="resource_auth_number" />
							</div>
                            <div class="deleteIcons" @click="handleDel(index, 'details')">
                                <i class="el-icon-circle-close"></i>
                            </div>
                        </div>
                    </draggable>
                </el-form-item>
			</div>
			<div class="footer flex-center">
				<el-button type="primary" @click="handlePost">确  认</el-button>
				<el-button @click="closeDialog(false)">取  消</el-button>
				<el-button type="primary" @click="handlePreView">预  览</el-button>
			</div>
		</el-form>
    </el-main>
</template>

<script>
    import {
		addGoods,
		editGoods
    } from "@/api/table";
    import draggable from 'vuedraggable';
    export default {
        name: "GOODS_ACTION",
        components: {
            draggable
        },
        props: {
            infoData: {
            	type: Object,
                default: {}
			},
			storeList: {
				type: Array,
                default: []
			},
			categoryDataList: {
				type: Array,
                default: []
			},
		},
        data() {
            return {
                openPreviewPage: false, // 预览
				formData: this.infoData,
				previewData: {},
				previewImageInfo: {},
				userId: '',
				dragTags: [],
                dragTagsDetails: [],
				showLoading: false,             
				access_token: {
                    access_token: this.$store.getters.token
                },
				uploadUrl: process.env[this.$base] + "/medias/image/upload",
            }
        },
      	methods: {
			updateData() {
				let { originPrice, minPrice, salePrice, listImageUrl, bannerList, detailList } = this.infoData;
				const data = {
					...this.infoData,
					originPrice: this.$util.prices(originPrice),
					minPrice: this.$util.prices(minPrice),
					salePrice: this.$util.prices(salePrice)
				}

				this.previewImageInfo = {
					detailType: 1,
					content: listImageUrl,
					position: 0,
					sort: 1
				};

				this.dragTagsDetails = detailList;
				this.dragTags = bannerList;
				this.formData = data;
			},
			handlePreView() {
				if (!this.dragTags.length) {
					this.$message.error("请上传图片再预览 O(∩_∩)O~");
					return
				}
				this.previewData = {
					...this.previewData,
					...this.formData
				}
				this.$event.emit('ShowGoodsPreviewPage', this.previewData);
			},
			// 选择商户
			handleChange(e) {
				this.formData.storeUid = e
			},
			// 商品分类
            checkCategory(e) {
                this.formData.categoryUid = e
            },
			handleClose() {
				this.openPreviewPage = false
            },
            // 限制数量后的超过数量的回调
            handleExceed(files, fileList) {
				this.$message.warning(`当前限制选择 6 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + this.dragTags.length} 个文件`);
			},

			// 限制数量后的超过数量的回调
			handleExceedMore(files, fileList) {
				this.$message.warning(`当前限制选择 12 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + this.dragTagsDetails.length} 个文件`);
			},
			// 图片上传前的钩子
			beforeUpload(file) {
				var type = "image/jpg,image/jpeg,image/png,image/gif";
				const isJPG = type.indexOf(file.type) != -1;
				const isLt1M = file.size / 1024 / 1024 < 1;

				if (!isJPG) {
					this.$message.error("上传图片只能是 JPG,JPEG,PNG,GIF 格式!");
				}
				if (!isLt1M) {
					this.$message.error("上传图片大小不能超过 1MB!");
				}
				return isJPG && isLt1M;
			},

			//上传之前格式和大小判断
			beforeAvatarUploadVideo(file) {
				const isLt100M = file.size / 1024 / 1024 < 100;
				if(!isLt100M) {
					this.$message.error("视频文件大小不能超过 100MB!");
				}
				return isLt100M
			},

			// 缩略图
			uploadPreviewSuccess(response, file, fileList) {
				if (response.code == "200") {
					const { fileUrl, fileUid } = response.data;
					this.$set(this.formData, 'listImageUrl', fileUrl);
                    this.previewImageInfo = {
                        detailType: 1,
						content: fileUrl,
						position: 0,
						sort: 1
                    };
				}
			},

			// 商品详情图
			uploadDetailsSuccess(response, file, fileList) {
				if (response.code == "200") {
                    const { fileUrl, fileUid } = response.data;
                    this.dragTagsDetails.push({
                        detailType: 1,
						content: fileUrl,
						position: 2
					});

					this.previewData.detailList = this.dragTagsDetails
				}
			},

			// 轮播图
			uploadBannersSuccess(response, file, fileList) {
				if (response.code == "200") {
                    const { fileUrl, fileUid } = response.data;
                    this.dragTags.push({
                        detailType: 1,
						content: fileUrl,
						position: 1
					});
					this.previewData.bannerList = this.dragTags
				}
            },
            
            getdata (evt) {
				console.log(evt.draggedContext.element, 'getdata')
			},
			datadragEnd (evt) {
				console.log('拖动前的索引 :' + evt.oldIndex)
				console.log('拖动后的索引 :' + evt.newIndex)
                console.log('banner: ', this.dragTags, 'details: ', this.dragTagsDetails)
			},

			// 确认
			handlePost() {
				// if (!Object.keys(this.previewImageInfo).length) {
				// 	this.$message.error('请添加缩略图');
				// 	return
				// }

				if (!this.dragTags.length) {
					this.$message.error('请添加轮播图');
					return
				}

				if (!this.dragTagsDetails.length) {
					this.$message.error('请添加商品详情图');
					return
				}

				const postData = [...[this.previewImageInfo], ...this.dragTags, ...this.dragTagsDetails];

				// sort不存在阻止提交数据
				const requiredData = postData.every(item => item.sort !== undefined)
				if (!requiredData) {
					this.$message({
						message: "含有未填写排序的图片！",
						type: "error"
					});
					return
				}

				this.$refs.actionform.validate(valid => {
					if (valid) {
						this.formData.productDetails = JSON.stringify(postData);
						delete this.formData.listImageUrl;
						let { originPrice, minPrice, salePrice } = this.formData;
						const data = {
							...this.formData,
							originPrice: this.$util.prices(originPrice, 'multiply'),
							minPrice: this.$util.prices(minPrice, 'multiply'),
							salePrice: this.$util.prices(salePrice, 'multiply')
						}
						this.previewData = data;
						this.showLoading = true;
						// 编辑
						if (data.productUid) {
							delete data.listImageUrl;
							delete data.bannerList;
							delete data.detailList;
							delete data.labels;
							editGoods(data).then(res => {
								if (res.data.isSuccessful !== "Y") {
									this.$message.error(res.data.message);
									return
								}
								this.$message({
									message: "编辑成功！",
									type: "success"
								});
								setTimeout(() => {
									this.closeDialog(true);
								}, 0);
							}).finally(() => {
								this.showLoading = false;
							});
							return
						}

						// 新增
						addGoods(data).then(res => {
							if (res.data.isSuccessful !== "Y") {
								this.$message.error(res.data.message);
								return
							}
							this.$message({
								message: "新增成功！",
								type: "success"
							});
							setTimeout(() => {
								this.closeDialog(true);
							}, 0);
						}).finally(() => {
							this.showLoading = false;
						});
					}
				})
			},

			closeDialog(refresh = false, type = ''){
				this.formData = {};
				this.$emit('func', {
					action: false,
					refresh,
					type
				})
			},

      		// 移除
			handleDel(index, type) {
				this.$confirm("移除操作, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    if (type === 'details') {
						this.dragTagsDetails.splice(index, 1)
      					this.$refs.uploadDetails.uploadFiles.splice(index, 1)
						// this.dragTagsDetails = this.dragTagsDetails.filter(item => item.content !== data.content);
						// console.log(this.dragTagsDetails, data.content)
                        return
					}
					this.dragTags.splice(index, 1)
      				this.$refs.uploadBanners.uploadFiles.splice(index, 1)
                    //  this.dragTags = this.dragTags.filter(item => item.content !== data.content);
				}).catch(() => {
					this.$message({
						type: "info",
						message: "已取消移除"
					});
				});
			}
      	},
  	}
</script>
<style lang="scss" scoped>
	.formItem {
		width: 360px;
    }
    .imgBoxWarpGrid {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .imgBoxWarpGrid-imgBox {
            position: relative;
            flex-direction: column;
            height: 120px;
            width: 120px;
            margin: 10px 15px;
            border: 1px solid #f8f8f8;
			border-radius: 5px;
            cursor: pointer;
            .deleteIcons {
				position: absolute;
				top: -18px;
				right: -5px;
			}
            .avatar {
                height: 80px;
                width: 80px;
                border-radius: 10px;
            }
			.resource_auth {
				font-size: 14px;
				&_number {
					width: 100px;
					text-align: center;
					.el-input__inner {
						text-align: center !important
					}
				}
			}
        }
    }
</style>

